package com.agent.generator.rabbitmq;

import com.agent.common.constant.CommonConstants;
import com.agent.generator.entity.GeneratedTask;
import com.agent.generator.service.AIGeneratorService;
import com.agent.generator.service.GeneratedTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * AI生成任务消息消费者
 * @author Jeff_Wan
 * @description 监听并处理任务队列中的生成任务
 */
@Slf4j
@Service
public class AiGenerateConsumer {

    private final GeneratedTaskService generatedTaskService;
    private final AIGeneratorService aiGeneratorService;

    @Autowired
    public AiGenerateConsumer(GeneratedTaskService generatedTaskService, AIGeneratorService aiGeneratorService) {
        this.generatedTaskService = generatedTaskService;
        this.aiGeneratorService = aiGeneratorService;
    }

    /**
     * 处理任务消息
     * @param taskId 任务ID
     */
    @RabbitListener(queues = "${rabbitmq.ai.generate.queue}")
    public void processTaskMessage(Long taskId) {
        log.info("Processing task: {}", taskId);

        try {
            GeneratedTask generatedTask = generatedTaskService.getTaskById(taskId);
            if (generatedTask == null) {
                log.error("Task not found: {}", taskId);
                return;
            }

            if (CommonConstants.ASSET_VIDEO.equals(generatedTask.getTaskType())) {
                aiGeneratorService.processVideoTask(generatedTask);
            } else if (CommonConstants.ASSET_IMAGE.equals(generatedTask.getTaskType())) {
                aiGeneratorService.processImageTask(generatedTask);
            } else {
                log.error("Unknown task type: {}", generatedTask.getTaskType());
            }
        } catch (Exception e) {
            log.error("Error processing task: {}", taskId, e);
        }
    }
}